package com.leador.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by lhy on 2016/9/11.
 */
public class SharedPreferUtils {
    private Context context;
    private SharedPreferences sharedPreferences;
    private Map<String, String> map;
    private Set<String> set;
    private static SharedPreferUtils INSTANCE = null;
    public static SharedPreferUtils getInstance(Context context){
        if(INSTANCE == null){
            synchronized (SharedPreferUtils.class){
                if(INSTANCE == null){
                    INSTANCE = new SharedPreferUtils(context);
                }
            }
        }
        return INSTANCE;
    }

    private SharedPreferUtils(Context context) {
        this.context = context;
        this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.context);
        this.map = new HashMap<String, String>();
        this.set = new HashSet<String>();
    }

    public final String getMap(String paramString) {
        if (!this.map.containsKey(paramString)) {
            this.map.put(paramString, this.sharedPreferences.getString(paramString, null));
        }
        return this.map.get(paramString);
    }

    public final void putMap(String paramString1, String paramString2) {
        this.map.put(paramString1, paramString2);
        if (!this.set.contains(paramString1)) {
            this.set.add(paramString1);
        }
    }

    public final boolean setMapToShared() {
        SharedPreferences.Editor editor = this.sharedPreferences.edit();
        Iterator iterator = this.set.iterator();
        while (iterator.hasNext()) {
            String str1 = (String)iterator.next();
            if (this.map.get(str1) == null) {
                editor.remove(str1);
            } else {
                editor.putString(str1,this.map.get(str1));
            }
        }
        boolean bool;
        if ((bool = editor.commit())) {
            this.set.clear();
        }
        return bool;
    }

}
